package service

import (
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
	"ruoyi-go/utils"
)

var SysConfigService = &sysConfigService{}

type sysConfigService struct{}

func (service sysConfigService) SelectConfigList(params tools.SearchTableDataParam, isPage bool) tools.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysRoles := params.Other.(system.SysConfig)
	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysConfig

	var db = mysql.MysqlDb().Model(&rows)

	var configId = sysRoles.ConfigId
	if configId != 0 {
		db.Where("config_id = ?", configId)
	}

	var configKey = sysRoles.ConfigKey
	if configKey != "" {
		db.Where("config_key = ?", configKey)
	}

	var configName = sysRoles.ConfigName
	if configName != "" {
		db.Where("config_name like concat('%', ?, '%')", configName)
	}

	var configType = sysRoles.ConfigType
	if configType != "" {
		db.Where("config_type = ?", configType)
	}

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	if beginTime != "" {
		startTime1, endTime1 := utils.GetBeginAndEndTime(beginTime, endTime)
		db.Where("create_time >= ?", startTime1)
		db.Where("create_time <= ?", endTime1)
	}

	if err := db.Count(&total).Error; err != nil {
		return tools.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	}

	if rows == nil {
		return tools.Fail()
	} else {
		return tools.Success(rows, total)
	}
}

func (service sysConfigService) SelectConfig(config system.SysConfig) system.SysConfig {
	var result system.SysConfig
	var dbg = mysql.MysqlDb().Model(&result)
	var configId = config.ConfigId
	if configId != 0 {
		dbg.Where("config_id = ?", configId)
	}
	var configKey = config.ConfigKey
	if configKey != "" {
		dbg.Where("config_key = ?", configKey)
	}
	err := dbg.First(&result).Error
	if err != nil {
		panic(err.Error())
	}
	return result
}

func (service sysConfigService) GetConfigInfo(configId interface{}) system.SysConfig {
	/*方式一*/
	//var sql = "select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark from sys_config where config_id = ?"
	var config system.SysConfig
	//mysql.MysqlDb().Raw(sql, configId).Find(&config)
	/*方式二*/
	err := mysql.MysqlDb().Where("config_id = ?", configId).First(&config).Error
	if err != nil {
		panic(err.Error())
	}
	return config
}

func (service sysConfigService) SaveConfig(config system.SysConfig) {
	/*参数键名是否存在*/
	var keyCount = service.checkConfigKeyUnique(config.ConfigKey)
	if keyCount > 0 {
		panic("新增参数'" + config.ConfigName + "'失败，参数键名已存在")
	}
	err := mysql.MysqlDb().Model(&system.SysConfig{}).Create(&config).Error
	if err != nil {
		panic(err.Error())
	}
}

func (service sysConfigService) checkConfigKeyUnique(configKey string) int64 {
	var keyCount int64
	err := mysql.MysqlDb().Model(&system.SysConfig{}).Where("config_key = ?", configKey).Count(&keyCount).Error
	if err != nil {
		panic(err.Error())
	}
	return keyCount
}

func (service sysConfigService) SelectConfigByKey(configKey string) string {
	var config system.SysConfig

	// 先从缓存中获取
	value := SysConfigCacheService.GetSysConfigCacheByKey(configKey)
	if value == "" {
		err := mysql.MysqlDb().Where("config_key = ?", configKey).First(&config).Error
		if err != nil {
			panic(err.Error())
		}
		// 放入缓存
		SysConfigCacheService.SetSysConfigCache(configKey, config.ConfigValue)
	}

	return config.ConfigValue
}

func (service sysConfigService) EditConfig(config system.SysConfig) {
	err := mysql.MysqlDb().Updates(&config).Error
	if err == nil {
		// 更新缓存
		SysConfigCacheService.SetSysConfigCache(config.ConfigKey, config.ConfigValue)
	} else {
		panic(err.Error())
	}
}

func (service sysConfigService) DelConfig(configIds string) {
	var ids = utils.Split(configIds)
	if len(ids) == 0 {
		panic("参数错误")
	}

	// 删除缓存
	var configKeys []string
	mysql.MysqlDb().Model(&system.SysConfig{}).Select("distinct config_key").Where("config_id in (?)", ids).Find(&configKeys)
	for _, configKey := range configKeys {
		SysConfigCacheService.DeleteSysConfigCache(configKey)
	}

	// 删除数据库
	for i := 0; i < len(ids); i++ {
		id := ids[i]
		service.DelConfigById(id)
	}
}

func (service sysConfigService) DelConfigById(configId int) {
	// 删除缓存
	var configKey string
	mysql.MysqlDb().Model(&system.SysConfig{}).Select("distinct config_key").Where("config_id = ？", configId).Find(&configKey)
	SysConfigCacheService.DeleteSysConfigCache(configKey)

	err := mysql.MysqlDb().Where("config_id = ?", configId).Delete(&system.SysConfig{}).Error
	if err != nil {
		panic(err.Error())
	}
}
